# TriggerSwitchD, executes commands to activate/deactive remote switches.
# (c) Copyright 2010 Pontus Strömdahl, AdhocSkill. 
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


require File.join(File.dirname(__FILE__),"protocol_loader")
require File.join(File.dirname(__FILE__),"..","code_converter")

module Tellstick
  module Nexa #:nodoc:
    include ProtocolLoader
    def turn_on(house,unit)
      output.puts "S#{codify(house)}#{codify(unit.to_s)}$k$k$kk$$kk$$kk$$}+"
    end
    def turn_off(house,unit)
      output.puts "S#{codify(house)}#{codify(unit.to_s)}$k$k$kk$$kk$$k$k$}+"
    end
    def teach(*args)
      turn_on(*args)
    end
    def output
      @output
    end
    
    private
    
    attr_reader :convert_it
    def convert_it
      @convert_it ||= CodeConverter.new([/[\d]+/,/[A-D]/,/[a-d]/],-1)
    end

    def codify(code)
      Nexa::adjust_result(convert_it.to_i(code)).reverse
    end

    def self.adjust_result(code)
      choices = %w{$k$k $kk$}
      translate_to_bit_array(code).map do |bit|
        choices[bit]
      end.reverse
    end

    def self.translate_to_bit_array(code)
      (0..3).map do
        val = (code & 1)
        code >>= 1
        val
      end
    end
  end
end